package com.sbs.gaoxinqutoilet.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;
import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.adapter.GaizaoTypeAdapter;
import com.sbs.gaoxinqutoilet.adapter.ToiletFilesRvAdapter;
import com.sbs.gaoxinqutoilet.base.BaseBackFragment;
import com.sbs.gaoxinqutoilet.entity.AddNewBuildTypeEntity;
import com.sbs.gaoxinqutoilet.entity.BuildFileItemEntity;
import com.sbs.gaoxinqutoilet.entity.CountyEntity;
import com.sbs.gaoxinqutoilet.entity.HomeMenuEntity;
import com.sbs.gaoxinqutoilet.entity.MessageEvent;
import com.sbs.gaoxinqutoilet.entity.UserEntity;
import com.sbs.gaoxinqutoilet.eventbus.EventCenter;
import com.sbs.gaoxinqutoilet.eventbus.StartNewFragmentEvent;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.BuildTypePopuListener;
import com.sbs.gaoxinqutoilet.interfaces.Constant;
import com.sbs.gaoxinqutoilet.interfaces.Constants;
import com.sbs.gaoxinqutoilet.interfaces.ContyPopuListener;
import com.sbs.gaoxinqutoilet.interfaces.EventConstant;
import com.sbs.gaoxinqutoilet.interfaces.PopuClickListener;
import com.sbs.gaoxinqutoilet.myapp.MyApplication;
import com.sbs.gaoxinqutoilet.utils.GsonTools;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.JsonUtil;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.NetworkUtils;
import com.sbs.gaoxinqutoilet.utils.SPUtil;
import com.sbs.gaoxinqutoilet.utils.StringUtil;
import com.sbs.gaoxinqutoilet.utils.appinstallerutils.ConvertUtils;
import com.sbs.gaoxinqutoilet.view.MyDFButton;
import com.zhy.autolayout.AutoFrameLayout;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.sbs.gaoxinqutoilet.R.id.file_address_conty;
import static com.sbs.gaoxinqutoilet.R.id.toolbar_back;

/**
 * Created by 聪明一只哈 on 2018/5/30.
 * Time: 2018/5/30  14:58
 */

public class ToiletFilesFragment extends BaseBackFragment {
    @BindView(toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_iv_menu)
    ImageView toolbarIvMenu;
    @BindView(R.id.toolbar_iv_add)
    ImageView toolbarIvAdd;
    @BindView(R.id.toolbar_tv_menu)
    TextView toolbarTvMenu;
    @BindView(R.id.toolbar_rl_menu)
    AutoRelativeLayout toolbarRlMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;


    @BindView(R.id.bt_filter)
    MyDFButton btFilter;
    @BindView(R.id.toiletfiles_rv)
    RecyclerView toiletfilesRv;
    @BindView(R.id.buytoiletfiles_trefresh)
    TwinklingRefreshLayout buytoiletfilesTrefresh;
    @BindView(R.id.toiletfiles_fl)
    AutoFrameLayout toiletfilesFl;
    @BindView(R.id.drawlayout)
    DrawerLayout drawLayout;

    @BindView(R.id.bt_file_huming)
    Button btFileHuming;
    @BindView(R.id.et_file_hum)
    EditText etFileHum;
    @BindView(R.id.toilet_et_doornum)
    EditText toiletEtDoornum;
    @BindView(R.id.toilet_et_address)
    EditText toiletEtAddress;
    @BindView(R.id.toilet_et_doorname)
    EditText toiletEtDoorname;
    @BindView(R.id.toilet_et_Iidnumber)
    EditText toiletEtIidnumber;
    @BindView(R.id.toilet_tv_unchange)
    TextView toiletTvUnchange;
    @BindView(R.id.toilet_tv_changing)
    TextView toiletTvChanging;
    @BindView(R.id.toilet_tv_changed)
    TextView toiletTvChanged;
    @BindView(R.id.toilet_tv_nonechange)
    TextView toiletTvNonechange;
    @BindView(R.id.toilet_tv_pull_choices)
    TextView toiletTvPullChoices;
    @BindView(R.id.toilet_tv_typeone)
    TextView toiletTvTypeone;
    @BindView(R.id.toilet_tv_typetwo)
    TextView toiletTvTypetwo;
    @BindView(R.id.toilet_tv_typethree)
    TextView toiletTvTypethree;
    @BindView(R.id.toilet_tv_typefour)
    TextView toiletTvTypefour;
    @BindView(R.id.toilet_tv_typefive)
    TextView toiletTvTypefive;
    @BindView(R.id.toilet_tv_typesix)
    TextView toiletTvTypesix;
    @BindView(R.id.toilet_tv_typeseven)
    TextView toiletTvTypeseven;
    @BindView(R.id.toilet_tv_typeeight)
    TextView toiletTvTypeeight;
    @BindView(R.id.toilet_tv_typesange)
    TextView toiletTypesange;
    @BindView(R.id.toilet_tv_typeqita)
    TextView toiletTypeqita;
    @BindView(R.id.all_sliding_licate)
    AutoLinearLayout allSlidingLicate;
    @BindView(file_address_conty)
    TextView fileAddressConty;
    @BindView(R.id.file_address_town)
    TextView fileAddressTown;
    @BindView(R.id.file_address_village)
    TextView fileAddressVillage;
    @BindView(R.id.tv_file_huce_count)
    TextView tvFileHuceCount;
    @BindView(R.id.toilet_tv_pull_statyear)
    TextView toiletTvPullStatyear;
    @BindView(R.id.toilet_tv_pull_buildtype)
    TextView toiletTvPullBuildtype;
    @BindView(R.id.toilet_reset)
    Button toiletReset;
    @BindView(R.id.toilet_done)
    Button toiletDone;
    Unbinder unbinder;

    //是否闲置
    List<String> buildstatelist = new ArrayList<>();
    //任务年份
    List<String> buildstateyearlist = new ArrayList<>();

    private ListPopupWindow buildstatePopupWindow;
    private int index;

    private View emptyView;
    private View errorView;
    private View footView;


    //解析数据成的集合
    private ArrayList<BuildFileItemEntity.DataBean> buyItemList;
    //数据适配器
    private ToiletFilesRvAdapter applyRvAdapter;
    //筛选条件对应的view,添加进集合
    private List<View> viewlist;
    //Rv一次性加载多少个条目,先写在这里,设为5条
    private int pageSize = 5;
    //传过来的改造档案数据  存储在Bundle中
    private static final String BUILD_FILE = "build_file";
    private HomeMenuEntity homemenu_buildfile;
    private BuildFileRequest builefileRequest;
    //筛选条件对应的集合
    private Map<String, String> conditionmap = new HashMap<>();
    private List<String> statuslist;
    private List<String> typelist;
    private ContyRequest cavRequest;
    private TwonRequest twonRequest;
    private VillageRequest villageRequest;
    private List<String> namelist = new ArrayList<>();
    private ListPopupWindow filecontyPW;
    private ListPopupWindow filetwonPW;
    private ListPopupWindow filevillagePW;
    private Button toiletToTop;
    private String token_data;
    private ListPopupWindow buildstatyearPopupWindow;
    private ListPopupWindow buildtypePopupWindow;
    private GaizaoTypeAdapter myBuildTypeAdapter;


    public static ToiletFilesFragment newInstance(HomeMenuEntity homeMenuEntity) {
        Bundle args = new Bundle();
        args.putSerializable(BUILD_FILE, homeMenuEntity);
        ToiletFilesFragment fragment = new ToiletFilesFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_toiletfiles, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView(inflater, view);
        initListener();
        return attachToSwipeBack(view);
    }

    /**
     * 初始化view
     *
     * @param inflater
     */
    private void initView(LayoutInflater inflater, View view) {
        EventBus.getDefault().register(this);

        token_data = SPUtil.getString(Constants.KEY_TOKEN, "");

        toiletToTop = (Button) view.findViewById(R.id.bt_to_top);

        toolbarTitle.setText("户厕改造档案");
        //返回按钮
        toolbarBack.setVisibility(View.VISIBLE);
        toolbarIvMenu.setVisibility(View.VISIBLE);
        toolbarIvMenu.setImageResource(R.drawable.shaixuan);



        //添加按钮
        //toolbarIvAdd.setVisibility(View.VISIBLE);
        toolbarIvAdd.setBackgroundResource(R.drawable.ic_add_black_24dp);

        //设置回键
        initToolbarBack(toolbar);
        //获取传递过来的值
        Bundle arguments = getArguments();
        if (arguments != null) {
            homemenu_buildfile = (HomeMenuEntity) arguments.getSerializable(BUILD_FILE);
        }

        //县级用户去掉新增
        UserEntity userEntity = MyApplication.getUserEntity();
        if(userEntity!=null){
            if("302".equals(userEntity.getOpt_level())){
                toolbarIvAdd.setVisibility(View.GONE);
            }else{
                toolbarIvAdd.setVisibility(View.VISIBLE);
            }
        }

        buildstatelist.add("下拉选择");
        buildstatelist.add("是");
        buildstatelist.add("否");

        buildstateyearlist.add("下拉选择");
        buildstateyearlist.add("2020年之前");
        buildstateyearlist.add("2020年");

        //添加刷新头和尾
        SinaRefreshView sinaHeader = new SinaRefreshView(_mActivity);
        sinaHeader.setArrowResource(R.drawable.arrow);
        sinaHeader.setTextColor(0xff745D5C);
        buytoiletfilesTrefresh.setHeaderView(sinaHeader);

        LoadingView loadingView = new LoadingView(_mActivity);
        buytoiletfilesTrefresh.setBottomView(loadingView);
        //设置是否禁用上下拉
        buytoiletfilesTrefresh.setEnableLoadmore(false);

        //初始化index
        index = 0;
        buyItemList = new ArrayList<>();
        applyRvAdapter = new ToiletFilesRvAdapter(R.layout.item_toilet_files, buyItemList);
        toiletfilesRv.setLayoutManager(new LinearLayoutManager(_mActivity));
        toiletfilesRv.setAdapter(applyRvAdapter);
        //默认第一次加载会进入回调
        applyRvAdapter.disableLoadMoreIfNotFullPage(toiletfilesRv);

        emptyView = inflater.inflate(R.layout.view_empty, toiletfilesRv, false);
        errorView = inflater.inflate(R.layout.view_error, toiletfilesRv, false);
        footView = inflater.inflate(R.layout.view_foot, toiletfilesRv, false);


    }


    /**
     * 监听
     */
    private void initListener() {
        //新增按钮的监听
        toolbarIvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new StartNewFragmentEvent(AddNewFileFragment.newInstance()));
            }
        });


        toolbarIvMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (drawLayout.isDrawerOpen(GravityCompat.END)) {
                    drawLayout.closeDrawer(GravityCompat.END);
                } else {
                    drawLayout.openDrawer(GravityCompat.END);
                }


                if (viewlist == null) {
                    viewlist = new ArrayList<>();
                }

                if (conditionmap != null) {
                    conditionmap.clear();
                }

                //改造状态value
                if (statuslist == null) {
                    statuslist = new ArrayList<>();
                }

                //改造类型value
                if (typelist == null) {
                    typelist = new ArrayList<>();
                }
            }
        });

        applyRvAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                ArrayList<BuildFileItemEntity.DataBean> list = (ArrayList<BuildFileItemEntity.DataBean>) adapter.getData();
                BuildFileItemEntity.DataBean dataBean = list.get(position);


                UserEntity userEntity = SPUtil.getBeanValue(Constants.KEY_USER, UserEntity.class);
                if (userEntity != null) {

                    //先判断是否闲置
                    if ("是".equals(dataBean.getXianzhi_n())) {
                        dataBean.setIs_edit(false);
                        EventBus.getDefault().post(new StartNewFragmentEvent(ToiletFilesDetialFragment.newInstance(dataBean)));
                    } else {


                        String opt_level = userEntity.getOpt_level();
                        if ("302".equals(opt_level)) {
                            dataBean.setIs_edit(false);
                            EventBus.getDefault().post(new StartNewFragmentEvent(ToiletFilesDetialFragment.newInstance(dataBean)));
                        } else {
//                        if("已改造".equals(dataBean.getGaizao_state_n())){
//                            dataBean.setIs_edit(false);
//                        }else{
//                            dataBean.setIs_edit(true);
//                        }
//                            if("旧有改造".equals(dataBean.getGaizao_state_n())){
//                                dataBean.setIs_edit(false);
//                            }else{
//                                dataBean.setIs_edit(true);
//                            }
                            dataBean.setIs_edit(true);
                            EventBus.getDefault().post(new StartNewFragmentEvent(ToiletFilesDetialFragment.newInstance(dataBean)));
                        }
                    }
                }
            }
        });

        buytoiletfilesTrefresh.setOnRefreshListener(new RefreshListenerAdapter() {
            //正在刷新
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                //设置时长
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("显示", "refreshRun");

                        if (conditionmap != null) {
                            conditionmap.clear();
                        }

                        requestRefresh();
                    }
                }, 2000);
            }

            //刷新完成
            @Override
            public void onFinishRefresh() {
                super.onFinishRefresh();
                LogUtils.i("显示", "Finishrefresh");
                //打开或关闭加载（一般用于下拉的时候做处理，因为上拉下拉不能同时操作）
                applyRvAdapter.setEnableLoadMore(true);

            }
        });
        //预加载
        applyRvAdapter.setPreLoadNumber(Constant.PRE_SIZE);
        //设置动画
        applyRvAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);

        applyRvAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                int currentSize = applyRvAdapter.getData().size();
                if (!TextUtils.isEmpty(mTotalSize)) {

                    int totalSize = Integer.parseInt(mTotalSize);
                    if (currentSize >= totalSize) {
                        applyRvAdapter.loadMoreEnd();
                    } else {
                        index++;

                        if (conditionmap != null && conditionmap.size() > 0) {
                            LogUtils.i("页数和列表数", "加载中含有查询条件:aa");
                            conditionLoadMore(conditionmap, index * pageSize, pageSize);
                        } else {
                            LogUtils.i("页数和列表数", "加载中: index:"
                                    + index + "~~pagesize:" + pageSize
                                    + "~~totalSize:" + totalSize
                                    + "~~currentSize:" + currentSize);
                            loadMoreData(index * pageSize, pageSize, conditionmap);
                        }


                    }
                }

            }
        }, toiletfilesRv);


        //响应键盘回车
        etFileHum.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    hideSoftInput();
                    String huname = v.getText().toString().trim();
                    if (!TextUtils.isEmpty(huname)) {
                        conditionmap.put("a.huming@m", huname);
                    }

                    index = 0;
                    conditionLoadMore(conditionmap, index, pageSize);
                    etFileHum.setText("");

                }

                return true;
            }
        });

    }

    boolean isSelectedUnChange, isSelectedBuilding, isSelectedBuiled, isSelectedBuildone,
            isSelectedone, isSelectedtwo, isSelectedthree, isSelectedfour, isSelectedfive,
            isSelectedsix, isSelectedseven, isSelectedeight, isSelectednine, isSelectedten;

    @OnClick({R.id.bt_filter, R.id.bt_file_huming,
            R.id.toilet_tv_unchange, R.id.toilet_tv_changing, R.id.toilet_tv_changed,
            R.id.toilet_tv_nonechange, R.id.toilet_tv_pull_choices, R.id.toilet_tv_typeone,
            R.id.toilet_tv_typetwo, R.id.toilet_tv_typethree, R.id.toilet_tv_typefour,
            R.id.toilet_tv_typefive, R.id.toilet_tv_typesix, R.id.toilet_tv_typeseven,
            R.id.toilet_tv_typeeight, R.id.toilet_reset, R.id.toilet_done,
            R.id.toilet_tv_typesange, R.id.toilet_tv_typeqita, R.id.bt_to_top,
            R.id.file_address_conty, R.id.file_address_town, R.id.file_address_village,
            R.id.toilet_tv_pull_statyear,R.id.toilet_tv_pull_buildtype})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //顶部户名筛选
            case R.id.bt_file_huming:
                String huname = etFileHum.getText().toString();
                if (!TextUtils.isEmpty(huname)) {
                    conditionmap.put("a.huming@m", huname);
                }
                index = 0;
                conditionLoadMore(conditionmap, index, pageSize);
                etFileHum.setText("");
                break;
            //回顶部
            case R.id.bt_to_top:
                toiletfilesRv.smoothScrollToPosition(0);
                break;

            //筛选按钮
            case R.id.bt_filter:

                break;

            //根据辖区单位进行筛选
            case R.id.file_address_conty:
                filecontyPW = new ListPopupWindow(_mActivity);
                setPopuDataList(view, filecontyPW, contylist);
                setPopuClickListenerList(new ContyPopuListener() {
                    @Override
                    public void show(CountyEntity Centity, String text) {
                        fileAddressConty.setText(Centity.getText());
                        //showLoadingDialog("正在加载乡镇数据");
                        SPUtil.putString(Constants.FILE_CONTY_LEVEL, "xian");
                        SPUtil.putString(Constants.FILE_CONTY_ID, Centity.getValue());

                        getTownList(Centity.getValue());
                    }
                });

                break;
            case R.id.file_address_town:
                String conty_address = fileAddressConty.getText().toString().trim();
                if (TextUtils.isEmpty(conty_address) || "(区)县".equals(conty_address)) {
                    showShortToast("请先选择县级单位");
                    return;
                } else {

                    try {
                        if (twonlist != null && twonlist.size() > 0) {
                            filetwonPW = new ListPopupWindow(_mActivity);
                            setPopuDataList(view, filetwonPW, twonlist);
                            setPopuClickListenerList(new ContyPopuListener() {
                                @Override
                                public void show(CountyEntity Centity, String text) {

                                    fileAddressTown.setText(Centity.getText());
                                    SPUtil.putString(Constants.FILE_CONTY_LEVEL, "xiang");
                                    SPUtil.putString(Constants.FILE_CONTY_ID, Centity.getValue());
                                    //showLoadingDialog("正在加载村级数据");
                                    getVillageList(Centity.getValue());

                                }
                            });
                        }
                    } catch (Exception e) {
                        Log.i("list为null", "乡级列表onViewClicked: " + e.toString());
                    }
                }

                break;
            case R.id.file_address_village:
                String town_address = fileAddressTown.getText().toString().trim();
                if (TextUtils.isEmpty(town_address) || "乡".equals(town_address)) {
                    showShortToast("请先选择乡级单位");
                    return;
                } else {
                    try {
                        if (villagelist != null && villagelist.size() > 0) {
                            filevillagePW = new ListPopupWindow(_mActivity);
                            setPopuDataList(view, filevillagePW, villagelist);
                            setPopuClickListenerList(new ContyPopuListener() {
                                @Override
                                public void show(CountyEntity Centity, String text) {
                                    fileAddressVillage.setText(Centity.getText());
                                    SPUtil.putString(Constants.FILE_CONTY_LEVEL, "cun");
                                    SPUtil.putString(Constants.FILE_CONTY_ID, Centity.getValue());
                                }
                            });
                        }
                    } catch (Exception e) {
                        Log.i("list为null", "村级列表onViewClicked: " + e.toString());
                    }
                }
                break;

            case R.id.toilet_tv_unchange:
                Log.i("isSelectedUnChange", "onViewClicked: " + isSelectedUnChange);
                if (!isSelectedUnChange) {
                    view.setSelected(true);
                    LogUtils.i("isSelectedUnChange", "蓝色");
                    statuslist.add("401");
                } else {
                    view.setSelected(false);
                    LogUtils.i("isSelectedUnChange", "灰色");
                    if (statuslist.contains("401")) {
                        statuslist.remove("401");
                    }
                }
                isSelectedUnChange = !isSelectedUnChange;

                //显示  未改造： 单坑+集中 三格式 水冲式 沼气池
//                toiletTvTypeeight.setVisibility(View.VISIBLE);
//                toiletTvTypefive.setVisibility(View.VISIBLE);
//                toiletTvTypesix.setVisibility(View.VISIBLE);
//                toiletTvTypeseven.setVisibility(View.VISIBLE);
//
//                //隐藏 双坑 双瓮 分集 其他 外建公厕
//                toiletTvTypetwo.setVisibility(View.GONE);
//                toiletTvTypethree.setVisibility(View.GONE);
//                toiletTvTypefour.setVisibility(View.GONE);
//                toiletTypeqita.setVisibility(View.GONE);
//                toiletTypesange.setVisibility(View.GONE);


                LogUtils.i("isSelectedUnChange", "onViewClicked: " + isSelectedUnChange);
                if (view.isSelected()) {
                    viewlist.add(view);
                }
                break;
            case R.id.toilet_tv_changing:
                if (!isSelectedBuilding) {
                    view.setSelected(true);
                    statuslist.add("402");
                } else {
                    view.setSelected(false);
                    if (statuslist.contains("402")) {
                        statuslist.remove("402");
                    }
                }
                isSelectedBuilding = !isSelectedBuilding;

                //显示  改造中： 单坑+集中 三格式 水冲式 沼气池
//                toiletTvTypeeight.setVisibility(View.VISIBLE);
//                toiletTvTypefive.setVisibility(View.VISIBLE);
//                toiletTvTypesix.setVisibility(View.VISIBLE);
//                toiletTvTypeseven.setVisibility(View.VISIBLE);
//
//                //隐藏 双坑 双瓮 分集 其他 外建公厕
//                toiletTvTypetwo.setVisibility(View.GONE);
//                toiletTvTypethree.setVisibility(View.GONE);
//                toiletTvTypefour.setVisibility(View.GONE);
//                toiletTypeqita.setVisibility(View.GONE);
//                toiletTypesange.setVisibility(View.GONE);

                if (view.isSelected()) {
                    viewlist.add(view);
                }
                break;
            case R.id.toilet_tv_changed:
                if (!isSelectedBuiled) {
                    view.setSelected(true);
                    statuslist.add("403");
                } else {
                    view.setSelected(false);
                    if (statuslist.contains("403")) {
                        statuslist.remove("403");
                    }
                }
                isSelectedBuiled = !isSelectedBuiled;


                //显示 已改造： 单坑+集中 三格式 水冲式 沼气池 外建公厕
//                toiletTvTypeeight.setVisibility(View.VISIBLE);
//                toiletTvTypefive.setVisibility(View.VISIBLE);
//                toiletTvTypesix.setVisibility(View.VISIBLE);
//                toiletTvTypeseven.setVisibility(View.VISIBLE);
//                toiletTypesange.setVisibility(View.VISIBLE);
//
//                //隐藏 双坑 双瓮 分集 其他
//                toiletTvTypetwo.setVisibility(View.GONE);
//                toiletTvTypethree.setVisibility(View.GONE);
//                toiletTvTypefour.setVisibility(View.GONE);
//                toiletTypeqita.setVisibility(View.GONE);

                if (view.isSelected()) {
                    viewlist.add(view);
                }
                break;
            case R.id.toilet_tv_nonechange:
                if (!isSelectedBuildone) {
                    view.setSelected(true);
                    statuslist.add("404");
                } else {
                    view.setSelected(false);
                    if (statuslist.contains("404")) {
                        statuslist.remove("404");
                    }
                }
                isSelectedBuildone = !isSelectedBuildone;

                //显示 三格式 水冲式 沼气池 双坑 双瓮 分集 其他
//                toiletTvTypetwo.setVisibility(View.VISIBLE);
//                toiletTvTypethree.setVisibility(View.VISIBLE);
//                toiletTvTypefour.setVisibility(View.VISIBLE);
//                toiletTypeqita.setVisibility(View.VISIBLE);
//                toiletTvTypefive.setVisibility(View.VISIBLE);
//                toiletTvTypesix.setVisibility(View.VISIBLE);
//                toiletTvTypeseven.setVisibility(View.VISIBLE);
//
//
//                //隐藏 外建公厕 单坑+集中
//                toiletTypesange.setVisibility(View.GONE);
//                toiletTvTypeeight.setVisibility(View.GONE);
                if (view.isSelected()) {
                    viewlist.add(view);
                }
                break;
            //是否闲置的下拉按钮
            case R.id.toilet_tv_pull_choices:
                buildstatePopupWindow = new ListPopupWindow(_mActivity);
                setPopuData(view, buildstatePopupWindow, buildstatelist);
                setPopuClickListener(new PopuClickListener() {
                    @Override
                    public void show(String mess) {
                        toiletTvPullChoices.setText(mess);
                        //添加到参数中
                        if (!"下拉选择".equals(mess)) {
                            conditionmap.put("xianzhi_n", mess);
                            if ("是".equals(mess)) {
                                conditionmap.put("xianzhi", "1");
                            } else if ("否".equals(mess)) {
                                conditionmap.put("xianzhi", "0");
                            }
                        }

                    }
                });
                break;
            //任务年份
            case R.id.toilet_tv_pull_statyear:

                buildstatyearPopupWindow = new ListPopupWindow(_mActivity);
                setPopuData(view, buildstatyearPopupWindow, buildstateyearlist);
                setPopuClickListener(new PopuClickListener() {
                    @Override
                    public void show(String mess) {
                        toiletTvPullStatyear.setText(mess);
                        //添加到参数中
                        if (!"下拉选择".equals(mess)) {
                            conditionmap.put("stat_year_n", mess);
                            if ("2020年之前".equals(mess)) {
                                conditionmap.put("stat_year", "2019");
                            } else if ("2020年".equals(mess)) {
                                conditionmap.put("stat_year", "2020");
                            }
                        }

                    }
                });

                break;

            //改造类型
            case R.id.toilet_tv_pull_buildtype:
                //获取改造类型数据
                getBuildTypeData(view);

                break;

            //改造类型的8中选择
            case R.id.toilet_tv_typeone:
                if (!isSelectedone) {
                    view.setSelected(true);
                    typelist.add("208");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("208")) {
                        typelist.remove("208");
                    }
                }
                isSelectedone = !isSelectedone;
                if (view.isSelected()) {
                    viewlist.add(view);
                }
                break;
            case R.id.toilet_tv_typetwo:
                if (!isSelectedtwo) {
                    view.setSelected(true);
                    typelist.add("205");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("205")) {
                        typelist.remove("205");
                    }
                }
                isSelectedtwo = !isSelectedtwo;
                if (view.isSelected()) {
                    viewlist.add(view);
                }
                break;
            case R.id.toilet_tv_typethree:
                if (!isSelectedthree) {
                    view.setSelected(true);
                    typelist.add("206");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("206")) {
                        typelist.remove("206");
                    }
                }
                isSelectedthree = !isSelectedthree;
                if (view.isSelected()) {
                    viewlist.add(view);
                }
                break;
            case R.id.toilet_tv_typefour:
                if (!isSelectedfour) {
                    view.setSelected(true);
                    typelist.add("207");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("207")) {
                        typelist.remove("207");
                    }
                }
                isSelectedfour = !isSelectedfour;
                if (view.isSelected()) {
                    viewlist.add(view);
                }
                break;
            case R.id.toilet_tv_typefive:
                if (!isSelectedfive) {
                    view.setSelected(true);
                    typelist.add("202");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("202")) {
                        typelist.remove("202");
                    }
                }
                isSelectedfive = !isSelectedfive;
                if (view.isSelected()) {
                    viewlist.add(view);
                }
                break;
            case R.id.toilet_tv_typesix:
                if (!isSelectedsix) {
                    view.setSelected(true);
                    typelist.add("203");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("203")) {
                        typelist.remove("203");
                    }
                }
                isSelectedsix = !isSelectedsix;
                if (view.isSelected()) {
                    viewlist.add(view);
                }
                break;
            case R.id.toilet_tv_typeseven:
                if (!isSelectedseven) {
                    view.setSelected(true);
                    typelist.add("201");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("201")) {
                        typelist.remove("201");
                    }
                }
                isSelectedseven = !isSelectedseven;
                if (view.isSelected()) {
                    viewlist.add(view);
                }
                break;
            case R.id.toilet_tv_typeeight:
                if (!isSelectedeight) {
                    view.setSelected(true);
                    typelist.add("210");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("210")) {
                        typelist.remove("210");
                    }
                }
                isSelectedeight = !isSelectedeight;
                if (view.isSelected()) {
                    viewlist.add(view);
                }
                break;

            case R.id.toilet_tv_typesange:
                if (!isSelectednine) {
                    view.setSelected(true);
                    typelist.add("204");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("204")) {
                        typelist.remove("204");
                    }
                }
                isSelectednine = !isSelectednine;
                if (view.isSelected()) {
                    viewlist.add(view);
                }

                break;


            case R.id.toilet_tv_typeqita:

                if (!isSelectedten) {
                    view.setSelected(true);
                    typelist.add("208");
                } else {
                    view.setSelected(false);
                    if (typelist.contains("208")) {
                        typelist.remove("208");
                    }
                }
                isSelectedten = !isSelectedten;
                if (view.isSelected()) {
                    viewlist.add(view);
                }

                break;

            case R.id.toilet_reset:
                for (View v : viewlist) {
                    v.setSelected(false);
                }
                resetbooleanstate();
                viewlist.clear();
                if (conditionmap != null) {
                    conditionmap.clear();
                }

                //置为空
                fileAddressConty.setText("(区)县");
                fileAddressTown.setText("乡");
                fileAddressVillage.setText("村");
                toiletEtAddress.setText("");
                toiletEtDoorname.setText("");
                toiletEtDoornum.setText("");
                toiletEtIidnumber.setText("");
                toiletTvPullBuildtype.setText("下拉选择");
                toiletTvPullStatyear.setText("下拉选择");
                toiletTvPullChoices.setText("下拉选择");
                break;
            case R.id.toilet_done:

                //辖区单位
                String addressConty = fileAddressConty.getText().toString();
                String addressTown = fileAddressTown.getText().toString();
                String addressvillage = fileAddressVillage.getText().toString();

                if (!"县".equals(addressConty) | !"乡".equals(addressTown) | !"村".equals(addressvillage)) {
                    String conty_level = SPUtil.getString(Constants.FILE_CONTY_LEVEL, "");
                    if ("xian".equals(conty_level)) {
                        if (conditionmap.containsKey("a.xiang_area_id")) {
                            conditionmap.remove("a.xiang_area_id");
                        }
                        if (conditionmap.containsKey("a.area_id")) {
                            conditionmap.remove("a.area_id");
                        }
                        conditionmap.put("a.xian_area_id", SPUtil.getString(Constants.FILE_CONTY_ID, ""));
                    } else if ("xiang".equals(conty_level)) {
                        if (conditionmap.containsKey("a.xian_area_id")) {
                            conditionmap.remove("a.xian_area_id");
                        }
                        if (conditionmap.containsKey("a.area_id")) {
                            conditionmap.remove("a.area_id");
                        }
                        conditionmap.put("a.xiang_area_id", SPUtil.getString(Constants.FILE_CONTY_ID, ""));
                    } else if ("cun".equals(conty_level)) {
                        if (conditionmap.containsKey("a.xian_area_id")) {
                            conditionmap.remove("a.xian_area_id");
                        }
                        if (conditionmap.containsKey("a.xiang_area_id")) {
                            conditionmap.remove("a.xiang_area_id");
                        }
                        conditionmap.put("a.area_id", SPUtil.getString(Constants.FILE_CONTY_ID, ""));
                    }
                }


                String hunumber = toiletEtDoornum.getText().toString();
                if (!TextUtils.isEmpty(hunumber)) {
                    conditionmap.put("a.hubianhao@m", hunumber);
                }

                //关闭侧滑放在return语句之后
                drawLayout.closeDrawer(GravityCompat.END);
                for (View v : viewlist) {
                    v.setSelected(false);
                }
                resetbooleanstate();
                //集合清空
                viewlist.clear();

                buildStatusSelect();

                buildtypeValue();

                index = 0;
                conditionLoadMore(conditionmap, index, pageSize);
                syso(conditionmap);

                //置为空
                toiletEtAddress.setText("");
                toiletEtDoorname.setText("");
                toiletEtDoornum.setText("");
                toiletEtIidnumber.setText("");
                toiletTvPullChoices.setText("下拉选择");//是否闲置
                toiletTvPullBuildtype.setText("下拉选择");
                toiletTvPullStatyear.setText("下拉选择");

                fileAddressConty.setText("(区)县");
                fileAddressTown.setText("乡");
                fileAddressVillage.setText("村");
                //状态重置
                typeStateReset();
                break;
        }
    }

    /**
     * 改造类型状态重置
     */
    private void typeStateReset() {
        toiletTvTypetwo.setVisibility(View.VISIBLE);
        toiletTvTypethree.setVisibility(View.VISIBLE);
        toiletTvTypefour.setVisibility(View.VISIBLE);
        toiletTypeqita.setVisibility(View.VISIBLE);
        toiletTvTypeeight.setVisibility(View.VISIBLE);
        toiletTvTypefive.setVisibility(View.VISIBLE);
        toiletTvTypesix.setVisibility(View.VISIBLE);
        toiletTvTypeseven.setVisibility(View.VISIBLE);
        toiletTypesange.setVisibility(View.VISIBLE);
    }


    //改造类型
    private List<AddNewBuildTypeEntity> addNewBuildTypeEntityList;
    private void getBuildTypeData(final View view) {
        showLoadingDialog("改造类型...");
        String the_last = HttpApis.addnew_last;
        LogUtils.i("第四个状态", "url: " + the_last);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestGet(_mActivity, the_last,map, new Request() {
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);
                LogUtils.i("第四个状态", "success: " + jsonStr);
                Type type = new TypeToken<ArrayList<AddNewBuildTypeEntity>>() {
                }.getType();
                addNewBuildTypeEntityList = JsonUtil.json2Collection(jsonStr, type);
                showBuildTypePopu(view);
                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);
                LogUtils.i("第四个状态", "error: " + error);
                cancelLoadingDialog();
            }
        });
    }

    private List<AddNewBuildTypeEntity> addnewtypelist = new ArrayList<>();
    private int buildtypeIndex = 0;
    private List<String> beanTypeList = new ArrayList<>();
    private List<String> beanTypeIDList = new ArrayList<>();
    private void showBuildTypePopu(View view) {

        addnewtypelist.clear();
        beanTypeList.clear();
        beanTypeIDList.clear();

        buildtypePopupWindow = new ListPopupWindow(_mActivity);
        setbuildTypePopuData(view, buildtypePopupWindow, addNewBuildTypeEntityList);

        setbuildTypePopuClickListener(new BuildTypePopuListener() {
            @Override
            public void show(List<AddNewBuildTypeEntity> datalist) {
                beanTypeList.clear();
                beanTypeIDList.clear();

                for (AddNewBuildTypeEntity abte : addnewtypelist) {
                    //beanTypeList.add(abte.getText());
                    beanTypeIDList.add(abte.getValue());
                }

                Collections.sort(beanTypeIDList);

                for (String idValue: beanTypeIDList) {
                    if("201".equals(idValue)){
                        beanTypeList.add("厕屋");
                    }
                    if("202".equals(idValue)){
                        beanTypeList.add("便器");
                    }
                    if("203".equals(idValue)){
                        beanTypeList.add("化粪池");
                    }
                }

                String buildtype_n = beanTypeList.toString();
                if(buildtype_n.contains("[")){
                    buildtype_n= StringUtil.deleteCharString(buildtype_n,'[');
                }
                if(buildtype_n.contains("]")){
                    buildtype_n= StringUtil.deleteCharString(buildtype_n,']');
                }
                if(buildtype_n.contains(" ")){
                    buildtype_n=StringUtil.deleteCharString(buildtype_n,' ');
                }
                String buildtype_Id = beanTypeIDList.toString();
                if(buildtype_Id.contains("[")){
                    buildtype_Id=StringUtil.deleteCharString(buildtype_Id,'[');
                }
                if(buildtype_Id.contains("]")){
                    buildtype_Id=StringUtil.deleteCharString(buildtype_Id,']');
                }
                if(buildtype_Id.contains(" ")){
                    buildtype_Id=StringUtil.deleteCharString(buildtype_Id,' ');
                }

                toiletTvPullBuildtype.setText(buildtype_n);
                if(!TextUtils.isEmpty(toiletTvPullBuildtype.getText().toString().trim())){
                    conditionmap.put("gaizao_type_n",buildtype_n);
                    conditionmap.put("gaizao_type",buildtype_Id);
                }

            }
        });
    }

    private void setbuildTypePopuData(View view, final ListPopupWindow mPopupWindow, final List<AddNewBuildTypeEntity> datalist) {

//        addnewtypelist.clear();
//        for (AddNewBuildTypeEntity abte : datalist) {
//            addnewtypelist.add(abte.getText());
//        }

        myBuildTypeAdapter = new GaizaoTypeAdapter(_mActivity, datalist);
        mPopupWindow.setAdapter(myBuildTypeAdapter);

        mPopupWindow.setVerticalOffset(ConvertUtils.dp2px(_mActivity, 16));


        //弹出的位置  弹出锚点
        mPopupWindow.setAnchorView(view);
        //设置宽高
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);

        mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键


        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

                for (AddNewBuildTypeEntity rb : addnewtypelist) {
                    beanTypeList.add(rb.getText());
                    beanTypeIDList.add(rb.getValue());
                }


                String buildtype_n = removeRepeat(beanTypeList).toString();
                if(buildtype_n.contains("[")){
                    buildtype_n= StringUtil.deleteCharString(buildtype_n,'[');
                }
                if(buildtype_n.contains("]")){
                    buildtype_n= StringUtil.deleteCharString(buildtype_n,']');
                }
                if(buildtype_n.contains(" ")){
                    buildtype_n=StringUtil.deleteCharString(buildtype_n,' ');
                }

                String beanType_id = removeRepeat(beanTypeIDList).toString();
                if(beanType_id.contains("[")){
                    beanType_id=StringUtil.deleteCharString(beanType_id,'[');
                }
                if(beanType_id.contains("]")){
                    beanType_id=StringUtil.deleteCharString(beanType_id,']');
                }
                if(beanType_id.contains(" ")){
                    beanType_id=StringUtil.deleteCharString(beanType_id,' ');
                }

                if(TextUtils.isEmpty(toiletTvPullBuildtype.getText().toString().trim())){

                    if(conditionmap.containsKey("gaizao_type_n")){
                        conditionmap.remove("gaizao_type_n");
                    }
                    if(conditionmap.containsKey("gaizao_type")){
                        conditionmap.remove("gaizao_type");
                    }
                }
//                conditionmap.put("gaizao_type_n",buildtype_n);
//                conditionmap.put("gaizao_type",beanType_id);

                beanTypeList.clear();
                beanTypeIDList.clear();
            }
        });


        //设置条目点击事件
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //使用回调,显示数据

                if (datalist.get(position).isSelected() == false) {
                    buildtypeIndex++;
                    addnewtypelist.add(datalist.get(position));
                    datalist.get(position).setSelected(true);
                } else {
                    buildtypeIndex--;
                    if (addnewtypelist.contains(datalist.get(position))) {
                        addnewtypelist.remove(datalist.get(position));
                    }
                    datalist.get(position).setSelected(false);
                }
                if (buildtypeIndex == 0) {
                    toiletTvPullBuildtype.setText("");
                    addnewtypelist.clear();
                    mPopupWindow.dismiss();
                } else {
                    //使用回调,显示数据
                    if (buildTypePopuListener != null) {
                        buildTypePopuListener.show(addnewtypelist);
                    }
                }

                myBuildTypeAdapter.notifyDataSetChanged();
            }
        });
        mPopupWindow.show();
    }

    public BuildTypePopuListener buildTypePopuListener;

    public void setbuildTypePopuClickListener(BuildTypePopuListener buildTypePopuListener) {
        this.buildTypePopuListener = buildTypePopuListener;
    }

    private List<String> removeRepeat(List<String> list) {
        List<String> no_list = new ArrayList<>();
        for (String show_str : list) {
            if (!no_list.contains(show_str)) {
                no_list.add(show_str);
            }
        }
        return no_list;
    }

    /**
     * 改造类型 单选或者双选
     */
    private void buildtypeValue() {
        StringBuilder statue_value = new StringBuilder();
        if (typelist != null && typelist.size() > 0) {
            if (typelist.size() > 1) {
                for (int i = 0; i < typelist.size(); i++) {
                    statue_value.append(typelist.get(i) + ",");
                }
            } else {
                statue_value.append(typelist.get(0));
            }
            String sv_temp = statue_value.toString().trim();
            if (sv_temp.endsWith(",")) {
                Log.i("statuevalue", "if: " + sv_temp);
                sv_temp = sv_temp.substring(0, statue_value.length() - 1);
                Log.i("statuevalue", "if: " + sv_temp);

            }
            conditionmap.put("a.gaizao_type@i", sv_temp);
        }
        typelist.clear();
    }

    /**
     * 改造状态  单选或者多选
     */
    private void buildStatusSelect() {
        StringBuilder statue_value = new StringBuilder();
        if (statuslist != null && statuslist.size() > 0) {
            if (statuslist.size() > 1) {
                //多个,多选,需要用","拼接value
                for (int i = 0; i < statuslist.size(); i++) {
                    statue_value.append(statuslist.get(i) + ",");
                }
            } else {
                //只有一个,单选,不用拼接value
                statue_value.append(statuslist.get(0));
            }

            String sv_temp = statue_value.toString().trim();
            if (sv_temp.endsWith(",")) {
                Log.i("testvalue", "if: " + sv_temp);
                sv_temp = sv_temp.substring(0, statue_value.length() - 1);
                Log.i("testvalue", "if: " + sv_temp);
            }
            conditionmap.put("a.gaizao_state@i", sv_temp);
        }
        statuslist.clear();
    }

    //模拟输出测验
    private void syso(Map<String, String> conditionmap) {
        Set<Map.Entry<String, String>> entrySet = conditionmap.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> me = iterator.next();
            String key = me.getKey();
            String value = me.getValue();

            Log.i("conditionmap", key + ":" + value);

        }

    }

    /**
     * 重置选择默认状态----->想个招,能不能将上边的代码抽取
     */
    private void resetbooleanstate() {
        isSelectedUnChange = false;
        isSelectedBuilding = false;
        isSelectedBuiled = false;
        isSelectedBuildone = false;
        isSelectedone = false;
        isSelectedtwo = false;
        isSelectedthree = false;
        isSelectedfour = false;
        isSelectedfive = false;
        isSelectedsix = false;
        isSelectedseven = false;
        isSelectedeight = false;
    }

    /**
     * 显示listpopuwindow,并使用回调,显示数据
     *
     * @param view
     * @param mPopupWindow
     * @param datalist
     */
    private void setPopuData(View view, final ListPopupWindow mPopupWindow, final List<String> datalist) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_list_item_1, datalist);
        mPopupWindow.setAdapter(adapter);
        //弹出的位置  弹出锚点
        mPopupWindow.setAnchorView(view);
        //设置宽高
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);

        mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键
        //设置条目点击事件
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //使用回调,显示数据
                if (popuClickListener != null) {
                    popuClickListener.show("" + datalist.get(position));
                }
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow.show();
    }

    public PopuClickListener popuClickListener;

    public void setPopuClickListener(PopuClickListener popuClickListener) {
        this.popuClickListener = popuClickListener;
    }


    /**
     * 显示listpopuwindow,并使用回调,显示数据
     *
     * @param view
     * @param mPopupWindow
     * @param datalists
     */

    private void setPopuDataList(View view, final ListPopupWindow mPopupWindow, final List<CountyEntity> datalists) {

        //清空集合,添加数据
        namelist.clear();
        for (CountyEntity ce : datalists) {
            namelist.add(ce.getText());
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_list_item_1, namelist);
        mPopupWindow.setAdapter(adapter);

        //弹出的位置  弹出锚点
        mPopupWindow.setAnchorView(allSlidingLicate);
        //设置宽高
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键
        //设置条目点击事件
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //使用回调,显示数据
                if (popuClickListenerList != null) {
                    popuClickListenerList.show(datalists.get(position), datalists.get(position).getText());
                }
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow.show();
    }

    public ContyPopuListener popuClickListenerList;

    public void setPopuClickListenerList(ContyPopuListener popuClickListenerList) {
        this.popuClickListenerList = popuClickListenerList;
    }

    /**
     * eventbus 页面跳转,事件接受
     *
     * @param center
     */
    @Subscribe
    public void onEventReceive(EventCenter center) {

        if (center.getEventCode() == EventConstant.UPLOAD_BUY_MODIFY) {
            //提交成功
            LogUtils.i("显示", "刷新");
            new Handler() {
            }.postDelayed(new Runnable() {
                @Override
                public void run() {
                    requestRefresh();
                }
            }, 500);
        }
    }


    /**
     * eventbus 页面跳转验证页面,事件接受
     * (threadMode = ThreadMode.MAIN)
     *
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent) {

        LogUtils.i("返回跳转", messageEvent.getMessage());
        if ("370".equals(messageEvent.getMessage())) {

            //清空conditionmap
            if(conditionmap!=null&&conditionmap.size()>0){
                conditionmap.clear();
            }

            //提交成功
            Log.i("返回跳转", messageEvent.getMessage());
            new Handler() {
            }.postDelayed(new Runnable() {
                @Override
                public void run() {

                    requestRefresh();
                }
            }, 500);
        }
    }


    /**
     * 页面条转过来就刷新数据
     */
    private void requestRefresh() {
        toiletToTop.setText("顶部");
        LogUtils.i("显示", "指示refresh " + index);
        //停止加载
        applyRvAdapter.setEnableLoadMore(false);
        //清空集合,将空集合设置进adapter
        buyItemList.clear();
        applyRvAdapter.setNewData(buyItemList);
        //设置出现刷新状态的头部
        if (buytoiletfilesTrefresh != null) {
            buytoiletfilesTrefresh.finishRefreshing();
        }
        index = 0;

        loadMoreData(index, pageSize, conditionmap);
    }

    /**
     * 页面加载动画结束就调用  loadMoreData(index, pageSize);
     * 所以  将两个方法紧挨着
     *
     * @param savedInstanceState
     */
    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        //添加家在逻辑
        LogUtils.i("显示", "指示enter " + index);
        loadMoreData(index, pageSize, conditionmap);
        //获取县乡村数据
        getLevelData();
    }


    /**
     * 获取县乡村数据
     */
    private void getLevelData() {
        //获取县,乡,村级列表数据
        //获取个人信息
        UserEntity userEntity = SPUtil.getBeanValue(Constants.KEY_USER, UserEntity.class);
        if (userEntity != null) {
            //获取县级列表
            getContyList(userEntity);
        }

    }


    //县级列表
    private List<CountyEntity> contylist = new ArrayList<>();
    //乡级列表
    private List<CountyEntity> twonlist = new ArrayList<>();
    //村级列表
    private List<CountyEntity> villagelist = new ArrayList<>();

    private void getContyList(UserEntity userEntity) {
        //需要拼接
        String addnew_url = HttpApis.addnew_info + userEntity.getArea_id() + "/" + "3";
        if (cavRequest == null) {
            cavRequest = new ContyRequest();
        }
        LogUtils.i("乡级列表", "url: " + addnew_url);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestGet(_mActivity, addnew_url,map, cavRequest);
    }

    private void getTownList(String conty_id) {
        String addnew_url = HttpApis.addnew_info + conty_id + "/" + "4";
        if (twonRequest == null) {
            twonRequest = new TwonRequest();
        }
        LogUtils.i("县级列表", "url: " + addnew_url);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestGet(_mActivity, addnew_url,map, twonRequest);
    }

    private void getVillageList(String teon_id) {
        String addnew_url = HttpApis.addnew_info + teon_id + "/" + "5";
        if (villageRequest == null) {
            villageRequest = new VillageRequest();
        }
        LogUtils.i("村级列表", "url: " + addnew_url);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token_data);
        HttpUtils.requestGet(_mActivity, addnew_url,map, villageRequest);
    }


    private class ContyRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);
            LogUtils.i("乡级列表", "success: " + jsonStr);
            Type type = new TypeToken<ArrayList<CountyEntity>>() {
            }.getType();
            contylist = JsonUtil.json2Collection(jsonStr, type);
        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("乡级列表", "error: " + error);
        }
    }

    private class TwonRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);

            LogUtils.i("县级列表", "success: " + jsonStr);

            Type type = new TypeToken<ArrayList<CountyEntity>>() {
            }.getType();
            twonlist = JsonUtil.json2Collection(jsonStr, type);
            cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("县级列表", "error: " + error);
            cancelLoadingDialog();
        }
    }

    private class VillageRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);
            LogUtils.i("村级列表", "success: " + jsonStr);
            Type type = new TypeToken<ArrayList<CountyEntity>>() {
            }.getType();
            villagelist = JsonUtil.json2Collection(jsonStr, type);
            cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("村级列表", "error: " + error);
            cancelLoadingDialog();
        }
    }


    /**
     * 加载数据
     *
     * @param index    页数
     * @param pageSize
     */
    private void loadMoreData(int index, int pageSize, Map<String, String> map_params) {
        if (index == 0) {
            showLoadingDialog();
        }
        Log.e("显示", "指示loadmore " + index);

        toiletToTop.setText("顶部");
        String mbuilfile_url = HttpApis.build_file_item;
        LogUtils.i("mbuilfile_url", mbuilfile_url);
        if (builefileRequest == null) {
            builefileRequest = new BuildFileRequest();
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("iud", homemenu_buildfile.getIud());
        params.put("start", String.valueOf(index));
        params.put("pagesize", String.valueOf(pageSize));
        params.put("token",token_data);
        HttpUtils.requestGet(_mActivity, mbuilfile_url, params, builefileRequest);

    }

    /**
     * 条件筛选
     *
     * @param conditionmap
     * @param index
     * @param pageSize
     */

    BuildFileRequestCondition builefileRequestcon;

    private void conditionLoadMore(Map<String, String> conditionmap, int index, int pageSize) {
        if (index == 0) {
            showLoadingDialog();
        }
        String mbuilfile_url = HttpApis.build_file_item;
        LogUtils.i("档案列表数据", mbuilfile_url);
        if (builefileRequestcon == null) {
            builefileRequestcon = new BuildFileRequestCondition();
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("iud", homemenu_buildfile.getIud());
        params.put("start", String.valueOf(index));
        params.put("pagesize", String.valueOf(pageSize));
        params.put("token",token_data);

        if (conditionmap != null && conditionmap.size() > 0) {
            params.putAll(conditionmap);
        }
        LogUtils.i("参数", "conditionLoadMore: " + params.size());
        HttpUtils.requestGet(_mActivity, mbuilfile_url, params, builefileRequestcon);


    }

    //请求列表数据
    private class BuildFileRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);
            LogUtils.i("档案列表数据", jsonStr);
            BuildFileItemEntity buildFileItemEntity = GsonTools.changeGsonToBean(jsonStr, BuildFileItemEntity.class);
            //将数据解析出来
            processSetData(buildFileItemEntity);
            //加载完
            applyRvAdapter.loadMoreComplete();
            if (index == 0) {
                cancelLoadingDialog();
            }
        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("档案列表数据", error);
            if (!NetworkUtils.isConnected(_mActivity)) {
                applyRvAdapter.setEmptyView(errorView);
            } else {
                applyRvAdapter.setEmptyView(emptyView);
                applyRvAdapter.loadMoreFail();
            }
            cancelLoadingDialog();
        }
    }

    //根据条件请求列表数据
    private class BuildFileRequestCondition extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);
            LogUtils.i("buildfile_condition", jsonStr);
            BuildFileItemEntity buildFileItemEntity = GsonTools.changeGsonToBean(jsonStr, BuildFileItemEntity.class);
            //将数据解析出来
            processSetDataCondition(buildFileItemEntity);
            //加载完
            applyRvAdapter.loadMoreComplete();
            if (index == 0) {
                cancelLoadingDialog();
            }

        }

        @Override
        public void error(String error) {
            super.error(error);
            LogUtils.i("buildfile_error", error);
            if (!NetworkUtils.isConnected(_mActivity)) {
                applyRvAdapter.setEmptyView(errorView);
            } else {
                applyRvAdapter.setEmptyView(errorView);
                applyRvAdapter.loadMoreFail();
            }
            cancelLoadingDialog();
        }
    }

    private void processSetDataCondition(BuildFileItemEntity buildFileItemEntity) {

        try{
            if (buildFileItemEntity != null) {
                mTotalSize = buildFileItemEntity.getRecordsTotal();
                toiletToTop.setText(mTotalSize);
                tvFileHuceCount.setText(mTotalSize+"户");
                //getHuNum(mTotalSize);
                if (Integer.parseInt(mTotalSize) > 0) {
                    if (index == 0) {
                        //设置新数据
                        applyRvAdapter.setNewData(buildFileItemEntity.getData());
                    } else {
                        applyRvAdapter.addData(buildFileItemEntity.getData());
                    }
                } else {
                    applyRvAdapter.setNewData(null);
                    applyRvAdapter.setEmptyView(emptyView);
                }
                LogUtils.i("显示", "数据u" + applyRvAdapter.getData().size());
            } else {
                applyRvAdapter.setEmptyView(emptyView);
            }
        }catch (Exception e){

        }



    }

    private String mTotalSize;
    //延时加载户数
    private void getHuNum(String mtotalsize){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                tvFileHuceCount.setText(mtotalsize+"户");
            }
        },200);
    }


    /**
     * 解析数据
     *
     * @param buildFileItemEntity
     */
    private void processSetData(BuildFileItemEntity buildFileItemEntity) {

        try {
            if (buildFileItemEntity != null) {

                mTotalSize = buildFileItemEntity.getRecordsTotal();
                if (Integer.parseInt(mTotalSize) > 0) {
                    tvFileHuceCount.setText(mTotalSize+"户");
                    //getHuNum(mTotalSize);
                    if (index == 0) {
                        //设置新数据
                        applyRvAdapter.setNewData(buildFileItemEntity.getData());
                    } else {
                        applyRvAdapter.addData(buildFileItemEntity.getData());
                    }
                } else {
                    applyRvAdapter.setEmptyView(emptyView);
                }
            } else {
                applyRvAdapter.setEmptyView(emptyView);
            }
        }catch (Exception e){

        }


    }

    @Override
    public boolean onBackPressedSupport() {

        if (drawLayout.isDrawerOpen(GravityCompat.END)) {
            drawLayout.closeDrawer(GravityCompat.END);
            return true;
        } else {
            return false;
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        LogUtils.i("hashqi", "onPause: ");
        OkHttpUtils.getInstance().cancelTag(this);
        cancelLoadingDialog();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
        OkHttpUtils.getInstance().cancelTag(this);
        cancelLoadingDialog();

    }


}
